<template>
  <div style="padding:20px">

    <!-- 搜索区 -->
    <div style="margin:10px 0">
      <el-select v-model="searchValue" @change="handleChange" class="m-2" placeholder="搜索类型" size="small"
        style="width:100px;margin-right: 10px;">
        <el-option v-for="item in searchOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-input placeholder="默认搜索民宿类型" v-model="search" clearable style="width:200px;margin-right: 10px;"></el-input>
      <el-button type="primary" @click="load">搜索</el-button>
    </div>
    <!-- 分页 -->
    <div style="margin:10px 0">
      <el-pagination v-model:currentPage="currentPage" v-model:page-size="pageSize" :page-sizes="[50, 100, 200, 300]"
        :small="small" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <!-- 列表 -->
    <el-table :data="tableData" border style="width: 100%" height="60vh" v-loading="loading" stripe>
      <el-table-column prop="id" label="ID" width="60" sortable />


      <el-table-column prop="name" label="民宿名称" width="100" />
      <el-table-column prop="code" label="房间号" />
      <el-table-column prop="device" label="设施" width="100" show-overflow-tooltip />
      <el-table-column prop="category" label="类型" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="seat" label="床位数" width="60" />
      <!-- <el-table-column label="预定状态" width="70">
          <template #default="scope">
            <el-button v-if="(scope.row.state === '空闲')" type="success" plain style="cursor:default">空闲</el-button>
            <el-button v-else-if="(scope.row.state === '预订' || scope.row.state === '预定')" type="primary" plain
              style="cursor:default">预订</el-button>
            <el-button v-else type="danger" plain style="cursor:default">入住</el-button>
          </template>
        </el-table-column> -->
      <el-table-column prop="weight" label="权重" width="60" sortable />
      <!-- <el-table-column prop="banner" label="banner" show-overflow-tooltip/> -->
      <el-table-column label="banner">
        <template #default="scope">
          <el-image style="width: 50px; height: 50px" :src="scope.row.banner" fit="cover"
            :preview-src-list="[scope.row.banner]" preview-teleported>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="city" label="所在城市" width="100" show-overflow-tooltip />
      <el-table-column prop="address" label="详细地址" width="100" show-overflow-tooltip />
      <el-table-column prop="describe" label="描述" />

      <!-- <el-table-column prop="createTime" label="创建日期" /> -->
      <el-table-column prop="updateTime" label="最后修改日期" />

      <el-table-column prop="remark" show-overflow-tooltip label="备注" />


      <el-table-column fixed="right" label="Operations" width="170">
        <template #default="scope">
          <!-- <HRoomImg :roomId="scope.row.id" /> -->
          <el-button type="primary" size="small" @click="handleSubscribe(scope.row, '预订'), dialogVisible = true">
            预订</el-button>
          <el-button type="success" size="small" @click="handleSubscribe(scope.row, '入住'), dialogVisible = true">
            直接入住</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--    弹窗提醒-->
    <el-dialog v-model="dialogVisible" title="房间操作" width="30%">
      <span>请选择入住/离开日期</span><br />
      <el-date-picker v-model="dateChoose" @blur="dateBlur" :default-time="defaultTime" type="daterange"
        range-separator="To" start-placeholder="入住日期" end-placeholder="离开日期" format="YYYY/MM/DD"
        value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="disabledDate" style="margin:10px" />
      <el-form :model="form" label-width="120px">

        <!-- 从按钮事件中获取 -->
        <el-form-item label="民宿ID">
          <el-input v-model="form.roomId" disabled style="width: 80%" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="房间号">
          <el-input v-model="form.roomCode" style="width: 80%" disabled></el-input>
        </el-form-item>
        <el-form-item label="事件">
          <el-input v-model="form.state" style="width: 80%" disabled></el-input>
        </el-form-item>
        <!-- 以下需要自行填写 -->
        <el-form-item label="入住人姓名">
          <el-input v-model="form.username" style="width: 80%" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label="入住人身份证号">
          <el-input v-model="form.idCard" style="width: 80%" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="入住人手机号">
          <el-input v-model="form.phone" style="width: 80%" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="入住日期">
          <el-input v-model="form.startDate" style="width: 80%" maxlength="20" disabled></el-input>
          <!-- <el-date-picker v-model="form.startDate" type="date" placeholder="Pick a day" size="small" /> -->
        </el-form-item>
        <el-form-item label="离开日期">
          <el-input v-model="form.endDate" style="width: 80%" maxlength="20" disabled></el-input>
        </el-form-item>
        <el-form-item label="入住天数(晚)">
          <el-input type="number" v-model="form.days" style="width: 80%" maxlength="20" disabled></el-input>
        </el-form-item>
        <el-form-item label="入住人数">
          <el-input v-model="form.amount" style="width: 80%" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="信息">
          <el-input type="textarea" v-model="form.userInfo" style="width: 80%"
            placeholder="多人入住请在此备注其余人身份信息！"></el-input>
        </el-form-item>
        <el-form-item label="用户前台备注">
          <el-input type="textarea" v-model="form.userRemark" style="width: 80%" placeholder="用户添加的备注"></el-input>
        </el-form-item>
        <el-form-item label="后台备注">
          <el-input type="textarea" v-model="form.remark" style="width: 80%" placeholder="用户看不到的备注"></el-input>
        </el-form-item>
        <el-form-item label="总价格">
          <el-input v-model="form.total" style="width: 80%"></el-input>
        </el-form-item>
      </el-form>
      <template #footer="target">
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="checkDate(), dialogVisible = false">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 支付弹窗 -->
    <el-dialog v-model="dialogVisible2" title="扫码支付" width="30%">
      <el-image src="http://localhost:8091/files/9c775d9e196e40b8968ca5ddbd5d3baa"></el-image>
      <template #footer="target">
        <span class="dialog-footer">
          <el-button @click="(dialogVisible2 = false)">暂不支付</el-button>
          <el-button type="primary" @click="dialogVisible2 = false, form.payState = 1, orderHandle()">支付成功</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
        
<script lang="ts">
import { defineComponent, onMounted, reactive, ref } from 'vue';
import request from '@/utils/request';
import { ElMessage } from 'element-plus'


export default defineComponent({
  name: 'HOrderSubscribeView',
  components: {

  },
  setup() {
    //加载动画
    const loading = ref(true)
    //表中数据
    const tableData = ref([])
    // 分页
    const currentPage = ref(1)
    const pageSize = ref(50)
    const total = ref(0)
    const small = ref(false)
    const background = ref(false)
    const disabled = ref(false)
    const handleSizeChange = (val: number) => { //改变每页数量
      console.log(`${val} items per page`)
      load()
    }
    const handleCurrentChange = (val: number) => { //改变当前页码位置
      console.log(`current page: ${val}`)
      load()
    }
    // 弹窗控制和数据
    const dialogVisible = ref(false)
    const dialogVisible2 = ref(false)
    const form: any = ref({})

    // table数据初始化
    const search = ref()
    const searchType = ref()
    const load = () => {
      request.get('/h/room/getFreeRoom', {
        params: {
          pageNum: currentPage.value,
          pageSize: pageSize.value,
          search: search.value,
          searchType: searchType.value
        }
      }).then(res => {
        // console.log(res.data)
        tableData.value = res.data.records
        total.value = res.data.total
        loading.value = false
      })
    }

    onMounted(() => {
      load()
    })


    // 搜索区域
    const searchValue = ref('')
    const searchOptions = [
      {
        value: 'name',
        label: '民宿名称',
      },
      {
        value: 'category',
        label: '民宿类型',
      },
      {
        value: 'device',
        label: '设施',
      },
      {
        value: 'city',
        label: '城市',
      }
    ]
    // 搜索类型
    const handleChange = (value: any) => {
      // console.log(value)
      searchType.value = value
    }
    // handleSubscribe 预订操作
    const handleSubscribe = (row: any, state: string) => {
      form.value = {}
      //跟表中数据隔离开，深拷贝，独立对象，避免点击取消数据丢失
      // form.value = JSON.parse(JSON.stringify(row))
      form.value.roomId = JSON.parse(JSON.stringify(row.id))
      form.value.roomCode = JSON.parse(JSON.stringify(row.code))
      form.value.total = row.price
      form.value.state = state
      dialogVisible.value = true
    }
    // orderHandle 订单处理
    const orderHandle = () => {

      request.post('/h/order', form.value).then((res: any) => {
        if (res.code === '0' || res.code === '200') {
          ElMessage.success('预订成功')
        } else {
          ElMessage.error('预订失败')
        }
        load()
      }).catch(err => {
        ElMessage.error('预订失败')
      })
    }

    // 日期选择器的处理
    const defaultTime = ref<[Date, Date]>([
      // 选择日期后开始/结束日期默认的时分秒
      new Date(2000, 1, 1, 0, 0, 0),
      new Date(2000, 2, 1, 23, 59, 59),
    ])
    const disabledDate = (time: Date) => {
      // 禁用今天以及之前的日期
      // return time.getTime() < Date.now()
      // 禁用昨天及之前的日期
      return time.getTime() < Date.now() - 24 * 60 * 60 * 1000

    }
    const dateChoose = ref([])
    const dateBlur = (e: FocusEvent) => {
      // console.log(dateChoose.value);
      form.value.startDate = dateChoose.value[0]
      form.value.endDate = dateChoose.value[1]
      // console.log(parseInt((dateChoose.value[1] - dateChoose.value[0]) / (1000 * 60 * 60 * 24)));
      form.value.days = GetNumberOfDays(dateChoose.value[0], dateChoose.value[1])
      if (form.value.days > 0) {
        form.value.total = form.value.total * form.value.days
      } else {
        form.value.days = 1
      }
    }
    const GetNumberOfDays = (date1: any, date2: any) => {//获得天数
      //date1：开始日期，date2结束日期
      const a1 = Date.parse(date1);
      const a2 = Date.parse(date2);
      //核心：时间戳相减，然后除以天数Math.floor((a2 - a1) / (1000 * 60 * 60 * 24))
      // return (a2 - a1) / (1000 * 60 * 60 * 24)
      return Math.floor((a2 - a1) / (1000 * 60 * 60 * 24))
    };
    const checkDate = () => {
      if (form.value.startDate == null || form.value.startDate == "") {
        dialogVisible2.value = false
        ElMessage.error('没有开始日期！！')
        return
      }
      if (form.value.endDate == null || form.value.endDate == "") {
        dialogVisible2.value = false
        ElMessage.error('没有结束日期！！')
        return
      }
      dialogVisible2.value = true
    }
    return {
      loading,
      tableData,
      search,
      currentPage,
      pageSize,
      total,
      small,
      background,
      disabled,
      handleSizeChange,
      handleCurrentChange,
      dialogVisible,
      dialogVisible2,
      form,
      load,
      searchValue,
      searchOptions,
      handleChange,
      handleSubscribe,
      orderHandle,
      dateBlur,
      dateChoose,
      checkDate,
      disabledDate,
      defaultTime
    }
  },
});
</script>

        